import { config } from "@/api/config";
import { handleCode } from "./code";
import { formatToken, getToken } from "../auth";

export type ResponseData<T> = {
  code: number;
  data: T;
  message?: string;
};

type Base = "HR" | "MANGMENT";

export interface RequestOptions extends Partial<RequestInit> {
  formData?: FormData;
}

export function getOptions(options?: RequestOptions): RequestInit {
  const token = getToken();
  const headers: Record<string, string> = {
    authorization: token ? formatToken(token) : ""
  };
  if (options?.formData) {
    options.body = options.formData;
  } else {
    headers["Content-Type"] = "application/json";
  }
  // 设置默认值
  const defaultOptions: RequestInit = {
    method: "GET",
    headers
  };
  return { ...defaultOptions, ...options };
}

export default async <T>(
  url: string,
  baseUrl: Base = "HR",
  option?: RequestInit
): Promise<ResponseData<T>> => {
  const newOption = getOptions(option);
  const newUrl = config[baseUrl] + url;
  try {
    const response = await fetch(newUrl, newOption);
    const res = await response.json();
    if (res.code !== 0) {
      handleCode(res);
      // return Promise.reject(res.message)
    }
    return res;
  } catch (error) {
    return Promise.reject(error);
  }
};
